package com.webster.isw.core.service.impl;

import com.webster.isw.core.gen.entity.ScScheduledLogCriteria;
import com.webster.isw.core.gen.mapper.ScScheduledLogMapper;
import com.webster.isw.core.gen.mapper.ScTriggerLogMapper;
import com.webster.isw.core.service.ScheduledJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * 计划任务服务
 * Created by Webster on 16/5/7.
 */
@Service("scheduledJobService")
public class ScheduledJobServiceImpl extends BaseServiceImpl implements ScheduledJobService {

    @Autowired
    private ScScheduledLogMapper scScheduledLogMapper;

    @Autowired
    private ScTriggerLogMapper scTriggerLogMapper;

    /**
     * Description: 清理计划任务日志
     */
    @Override
    public void clearScheduledLog() {
        Calendar cd = getExpiredCalendar("SCHEDULED_LOG_KEEP_DAY");

        // 条件
        ScScheduledLogCriteria criteria = new ScScheduledLogCriteria();
        criteria.createCriteria().andCreateAtLessThanOrEqualTo(cd.getTime());

        // 删除
        scScheduledLogMapper.deleteByExample(criteria);
    }


    /**
     * Description: 清理计划任务执行日志
     */
    @Override
    public void clearTriggerLog() {
        Calendar cd = getExpiredCalendar("TRIGGER_LOG_KEEP_DAY");

        // 条件
        ScScheduledLogCriteria criteria = new ScScheduledLogCriteria();
        criteria.createCriteria().andCreateAtLessThanOrEqualTo(cd.getTime());

        // 删除
        scScheduledLogMapper.deleteByExample(criteria);
    }

    private Calendar getExpiredCalendar(String paramName) {
        // 获取参数
        String scheduledLogKeepTime = getParamService().getSysParamPreFerDefault(paramName);

        // 计算归档日期
        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date());
        cd.add(Calendar.DATE, 0 - Integer.parseInt(scheduledLogKeepTime));
        return cd;
    }
}
